#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;

/*Prototype*/
void gotoxy(int ,int);
int main()
{
    /* variable*/
    int n,so;
    int i,x,y;
    int tp,tx,pt,dl;
    /*Processing*/
    cout << "Nhap kich thuoc ma tran: ";
    cin >> n;
    so = 0;
    tp =n;
    tx = n;
    pt = 1;
    dl = 2;
    y=1;x =0;
    system("cls");
    while (so != n*n)
    {

        while((x < tp) && (so != n*n))
        {
            ++x;
            ++so;
            gotoxy(x*3,y*3);
            cout <<so;
        }
        tp -= 1;

        while((y < tx) && (so != n*n))
        {
            ++y;
            ++so;
            gotoxy(x*3,y*3);
            cout << so;
        }
        tx -= 1;

        while((x > pt) && (so != n*n))
        {
            --x;
            ++so;
            gotoxy(x*3,y*3);
            cout << so;
        }
        pt +=1;

        while((y > dl) && (so != n*n))
        {
            --y;
            ++so;
            gotoxy(x*3,y*3);
            cout << so;
        }
        dl +=1;
    }
    gotoxy(1,n*3);
	getch();
    return 0;
}//end main

void gotoxy(int x, int y){
    COORD c;
    c.X = x -1;
    c.Y = y -1;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);
}
